package com.huashi.dealer.modular.business.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.OrderGoods;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.modular.business.order.mapper.OrderGoodsMapper;
import com.huashi.dealer.modular.business.order.service.OrderGoodsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单商品Service实现类
 */
@Slf4j
@Service("apiOrderGoodsServiceImpl")
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements OrderGoodsService {

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Override
    public List<OrderGoods> getOrderGoodsByOrderId(Integer orderId) {
        log.info("查询订单商品，orderId={}", orderId);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getOrderId, orderId)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByUserId(Integer userId) {
        log.info("查询用户订单商品，userId={}", userId);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getUserId, userId)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByGoodsId(Integer goodsId) {
        log.info("查询商品订单商品，goodsId={}", goodsId);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getGoodsId, goodsId)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public OrderGoods getOrderGoodsByOrderIdAndGoodsId(Integer orderId, Integer goodsId) {
        log.info("查询订单商品，orderId={}, goodsId={}", orderId, goodsId);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getOrderId, orderId)
                .eq(OrderGoods::getGoodsId, goodsId)
                .eq(OrderGoods::getIsDelete, 0);
        return orderGoodsMapper.selectOne(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByWxappId(Integer wxappId) {
        log.info("查询小程序订单商品，wxappId={}", wxappId);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getWxappId, wxappId)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByOrderIds(List<Integer> orderIds) {
        log.info("批量查询订单商品，orderIds={}", orderIds);
        if (orderIds == null || orderIds.isEmpty()) {
            return List.of();
        }
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OrderGoods::getOrderId, orderIds)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByCommentStatus(Integer isComment) {
        log.info("查询订单商品评价状态，isComment={}", isComment);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getIsComment, isComment)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByExpressStatus(Integer isOrderExpress) {
        log.info("查询订单商品发货状态，isOrderExpress={}", isOrderExpress);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getIsOrderExpress, isOrderExpress)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    public List<OrderGoods> getOrderGoodsByType(Integer isType) {
        log.info("查询订单商品类型，isType={}", isType);
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderGoods::getIsType, isType)
                .eq(OrderGoods::getIsDelete, 0)
                .orderByDesc(OrderGoods::getCreateTime);
        return orderGoodsMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrderGoods(OrderGoods orderGoods) {
        log.info("添加订单商品: {}", orderGoods);
        if (orderGoods == null) {
            log.error("添加订单商品失败，参数为空");
            throw new CommonException("订单商品信息不能为空");
        }
        return orderGoodsMapper.insert(orderGoods) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderGoods(OrderGoods orderGoods) {
        log.info("更新订单商品: {}", orderGoods);
        if (orderGoods == null || orderGoods.getOrderGoodsId() == null) {
            log.error("更新订单商品失败，参数为空");
            throw new CommonException("订单商品信息不能为空");
        }
        return orderGoodsMapper.updateById(orderGoods) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrderGoods(Integer orderGoodsId) {
        log.info("删除订单商品，orderGoodsId={}", orderGoodsId);
        if (orderGoodsId == null) {
            log.error("删除订单商品失败，参数为空");
            throw new CommonException("订单商品ID不能为空");
        }
        LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderGoods::getOrderGoodsId, orderGoodsId)
                .set(OrderGoods::getIsDelete, 1);
        return orderGoodsMapper.update(null, wrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAddOrderGoods(List<OrderGoods> orderGoodsList) {
        log.info("批量添加订单商品: {}", orderGoodsList);
        if (orderGoodsList == null || orderGoodsList.isEmpty()) {
            log.error("批量添加订单商品失败，参数为空");
            throw new CommonException("订单商品列表不能为空");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrderGoodsByOrderId(Integer orderId) {
        log.info("根据订单ID删除订单商品，orderId={}", orderId);
        if (orderId == null) {
            log.error("根据订单ID删除订单商品失败，参数为空");
            throw new CommonException("订单ID不能为空");
        }
        LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderGoods::getOrderId, orderId)
                .set(OrderGoods::getIsDelete, 1);
        return orderGoodsMapper.update(null, wrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommentStatus(Integer orderGoodsId, Integer isComment) {
        log.info("更新订单商品评价状态，orderGoodsId={}, isComment={}", orderGoodsId, isComment);
        if (orderGoodsId == null) {
            log.error("更新订单商品评价状态失败，参数为空");
            throw new CommonException("订单商品ID不能为空");
        }
        LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderGoods::getOrderGoodsId, orderGoodsId)
                .set(OrderGoods::getIsComment, isComment);
        return orderGoodsMapper.update(null, wrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateExpressStatus(Integer orderGoodsId, Integer isOrderExpress) {
        log.info("更新订单商品发货状态，orderGoodsId={}, isOrderExpress={}", orderGoodsId, isOrderExpress);
        try {
            LambdaUpdateWrapper<OrderGoods> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(OrderGoods::getOrderGoodsId, orderGoodsId)
                    .set(OrderGoods::getIsOrderExpress, isOrderExpress);
//                    .set(OrderGoods::getUpdateTime, (int) (System.currentTimeMillis() / 1000));
            return orderGoodsMapper.update(null, wrapper) > 0;
        } catch (Exception e) {
            log.error("更新订单商品发货状态失败：", e);
            throw new CommonException("更新订单商品发货状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean backGoodsStock(OrderGoods orderGoods) {
        log.info("回退商品库存，orderGoodsId={}, goodsId={}, totalNum={}", 
                orderGoods.getOrderGoodsId(), orderGoods.getGoodsId(), orderGoods.getTotalNum());
        try {
            // TODO: 实现商品库存回退逻辑
            // 这里需要注入GoodsMapper和GoodsSkuMapper
            // 1. 更新商品总库存
            // LambdaUpdateWrapper<Goods> goodsWrapper = new LambdaUpdateWrapper<>();
            // goodsWrapper.eq(Goods::getGoodsId, orderGoods.getGoodsId())
            //         .setSql("goods_stock = goods_stock + " + orderGoods.getTotalNum());
            // goodsMapper.update(null, goodsWrapper);
            
            // 2. 更新商品SKU库存
            // LambdaUpdateWrapper<GoodsSku> skuWrapper = new LambdaUpdateWrapper<>();
            // skuWrapper.eq(GoodsSku::getGoodsId, orderGoods.getGoodsId())
            //         .eq(GoodsSku::getSpecSkuId, orderGoods.getSpecSkuId())
            //         .setSql("stock_num = stock_num + " + orderGoods.getTotalNum());
            // goodsSkuMapper.update(null, skuWrapper);
            
            log.info("回退商品库存成功：商品ID={}, 数量={}", orderGoods.getGoodsId(), orderGoods.getTotalNum());
            return true;
        } catch (Exception e) {
            log.error("回退商品库存失败：", e);
            throw new CommonException("回退商品库存失败：" + e.getMessage());
        }
    }
} 